<template>
    <div class="container">
        <div class="left-panel">
            <h2>上传图片</h2>
            <input class="file-input" type="file" @change="handleFileUpload" />
            <button class="upload-button" @click="uploadImage">上传</button>
            <h2>最近上传的图片</h2>
            <div class="image-container">
                <img v-if="currentImage" :src="getImageUrl(currentImage.image)" alt="uploaded image" />
                <p v-else>没有图片</p>
            </div>
        </div>
        <div class="right-panel">
            <h2>检测结果</h2>
            <div class="chart-container" ref="barChart"></div>
            <div class="chart-container" ref="pieChart"></div>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';
import { uploadImage, getUserImages } from '@/api/inspection'

export default {
    data() {
        return {
            selectedFile: null,
            currentImage: null,
            detectionResult: null,
            images: []
        };
    },
    methods: {
        handleFileUpload(event) {
            this.selectedFile = event.target.files[0];
        },
        async uploadImage() {
            if (!this.selectedFile) return;

            const formData = new FormData();
            formData.append('file', this.selectedFile);

            try {
                await uploadImage(formData);
                this.$message.success('上传成功');
                this.fetchImages();
            } catch (error) {
                this.$message.error('上传失败');
                console.error('上传失败:', error);
            }
        },
        async fetchImages() {
            try {
                const response = await getUserImages();
                this.images = response.data;
                if (this.images.length > 0) {
                    this.currentImage = this.images[this.images.length - 1];
                    this.fetchDetectionResults(this.currentImage.id);
                }
            } catch (error) {
                this.$message.error('获取图片列表失败');
                console.error('获取图片列表失败:', error);
            }
        },
        async fetchDetectionResults(imageId) {
            try {
                const response = await axios.get('http://localhost:8000/api/results/', {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    },
                    params: {
                        image_id: imageId
                    }
                });
                this.detectionResult = response.data[0];  // 假设只获取最新的一条检测结果
                this.drawCharts();
            } catch (error) {
                console.error('获取检测结果失败', error);
            }
        },
        getImageUrl(imagePath) {
            return `http://localhost:8000${imagePath}`;
        },
        drawCharts() {
            this.drawBarChart();
            this.drawPieChart();
        },
        drawBarChart() {
            const barChart = echarts.init(this.$refs.barChart);
            const option = {
                title: {
                    text: '检测结果 - 柱状图'
                },
                tooltip: {},
                xAxis: {
                    type: 'category',
                    data: ['老鼠数量', '裸体人数', '垃圾桶数量', '刀具数量', '煤气罐数量']
                },
                yAxis: {
                    type: 'value'
                },
                series: [{
                    type: 'bar',
                    data: [
                        this.detectionResult.rats,
                        this.detectionResult.naked_people,
                        this.detectionResult.trash_bins,
                        this.detectionResult.knives,
                        this.detectionResult.gas_cylinders
                    ]
                }]
            };

            barChart.setOption(option);
        },
        drawPieChart() {
            const pieChart = echarts.init(this.$refs.pieChart);
            const option = {
                title: {
                    text: '检测结果 - 饼图'
                },
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    top: '5%',
                    left: 'center'
                },
                series: [
                    {
                        name: '检测结果',
                        type: 'pie',
                        radius: '50%',
                        data: [
                            { value: this.detectionResult.rats, name: '老鼠数量' },
                            { value: this.detectionResult.naked_people, name: '裸体人数' },
                            { value: this.detectionResult.trash_bins, name: '垃圾桶数量' },
                            { value: this.detectionResult.knives, name: '刀具数量' },
                            { value: this.detectionResult.gas_cylinders, name: '煤气罐数量' }
                        ],
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            };

            pieChart.setOption(option);
        }
    },
    created() {
        this.fetchImages();
    }
};
</script>

<style scoped>
.container {
    display: flex;
    height: 100%;
    flex-direction: row;
    justify-content: space-between;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.left-panel,
.right-panel {
    width: 48%;
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #ffffff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
}

h2 {
    color: #333;
    margin-bottom: 20px;
}

.file-input {
    margin-bottom: 20px;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    width: 100%;
}

.upload-button {
    background-color: #42b983;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s;
    width: 100%;
    margin-bottom: 20px;
}

.upload-button:hover {
    background-color: #369f72;
}

.image-container {
    width: 300px;
    height: 300px;
    border: 1px solid #ddd;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    margin-top: 10px;
    background-color: #f5f5f5;
    border-radius: 4px;
}

img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
}

.chart-container {
    width: 100%;
    height: 300px;
    margin-top: 20px;
}
</style>